// miniprogram/pages/Schedule/index.js
import {convertToChinaNum,getmatchshortname} from '../../utils/utils';
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    staticUrl: app.globalData.staticUrl,
    logoUrl: app.globalData.imagelogourl,
    avatarUrl: app.globalData.imageunlogurl,
    currentTab: 0,
    selectyearlists:[2023,2022],
    schuedelDataByMonth: undefined,
    currentpageheight: 0,
    baseimgaeUrl: app.globalData.imageBaseUrl,
    sponsorlogoes: [],
    indexpageUrl:[],
    selectyear: new Date().getFullYear(),
    matchinforeg:[],
    listtype:'list',//'map',
    isfull:false,
    markers :[],
    selectarea:'全国',
    selectmt_type:0,
    customCallout:{
      display:'BYCLICK',
      anchorX:0,
      anchorY:0,
    },
    location:{
      longitude:108.552500,
      latitude:34.322700
    },

    limitbonds:{
      southwest:{latitude:24.961451,longitude:76.008302},
      norteast:{latitude:53.848845,longitude:134.508028},
    },
    lables:[],
    setting : {
      skew: 0,
      rotate: 0,
      showLocation: false,
      showScale: false,
      subKey: '',
      layerStyle: 1,
      enableZoom: true,
      enableScroll: true,
      enableRotate: false,
      showCompass: false,
      enable3D: false,
      enableOverlooking: false,
      enableSatellite: false,
      enableTraffic: false,
    },
    titlecontent:"",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    
    /*wx.getLocation({
      type: 'wgs84',
      success: (result) => {
        const latitude = result.latitude
        const longitude = result.longitude
        const speed = result.speed
        const accuracy = result.accuracy
     
        wx.setStorageSync('location', {lng:longitude,lat:latitude});
      },
      fail: (res) => {},
      complete: (res) => {},
    })*/


    //initmap
/*
    const mapCtx = this.selectAllComponents('#matchmap');
    console.log(mapCtx);
    //设置地图限制区域
    mapCtx.setOption({
      restrict:{
        southwest:{latitude:24.961451,longitude:76.008302},
        norteast:{latitude:53.848845,longitude:134.508028},
        bounds:[
          {latitude:52.947065,longitude:103.674851},
          {latitude:3.199467,longitude:106.412983},
          {latitude:39.246256,longitude:73.612434},
          {latitude:48.320802,longitude:134.82111},
        ],
        padding:[50,50,50,50]
      }
  }) */

    var activityid ,userID;
    var scene = decodeURIComponent(options.scene);
    var params = scene.split("&");
    if(scene && params.length>1){
     
      console.log(params);
      if (params.length == 1) {

        activityid = params[0].split("=")[1];
      } else if (params.length == 2) {
        activityid = params[0].split("=")[1];
        userID = params[1].split("=")[1];
      } 
      console.log(activityid);
      console.log(userID);

      this.setData({activityid:activityid});
    }

    console.log(scene);

    this.setData({
      sponsorlogoes: app.globalData.sponsorlogoes,
      logoUrl: app.globalData.imagelogourl,
    });
    var that = this;
    if(!this.data.sponsorlogoes){
      app.getlogoes(function(res){
        if(res.data.data){
          console.log("sponsorlogoes");
          console.log(res.data.data);
          that.setData({sponsorlogoes:res.data.data.loges});
          app.globalData.sponsorlogoes = that.data.sponsorlogoes.loges;
          if(res.data.data.ads ){
            app.globalData.bannerAd = res.data.data.ads;
            wx.setStorageSync('AD',  app.globalData.bannerAd);
          }
          else{
            app.globalData.bannerAd ="";
            wx.setStorageSync('AD',  app.globalData.bannerAd);
          }
        }
      
      },0);
    };

    this.getIndexpics();
   ///获取正在报名的比赛
    this.getmatchinforeg();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.getschedule();

  },
  onResize: function (res) {
    this.onShow();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1
      })
    }
    if(wx.getStorageSync('location')){
      //console.log(wx.getStorageSync('location'));
      this.setData({locallocation:wx.getStorageSync('location')})
      
    }
    var that = this;
    /*({
      type:'wgs84',
      success:function(res){
        console.log(res)

        var locallocation = {latitude:res.latitude,longitude: res.longitude};

        that.setData({locallocation:locallocation})
        wx.setStorageSync('location', locallocation);
      }
    })*/
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },



  regionchange:function(e){
    console.log(e);
    if(e.detail.type == "begin"){
      return;
    }
    const {latitude , longitude} = e.detail.centerLocation;
    const {limitbonds,location} = this.data;
    if(latitude < limitbonds.southwest.latitude ){
      //超出西南角纬度范围,设置为西南角纬度
      location.latitude = limitbonds.southwest.latitude
      this.setData({
        location
      })
    } else  if(latitude > limitbonds.norteast.latitude ){
      //超出东北角纬度范围,设置为东北角纬度

      location.latitude = limitbonds.norteast.latitude
      this.setData({
        location
      })
    }

    if(longitude <limitbonds.southwest.longitude ){
       //超出西南角经度范围,设置为西南角经度
       
        location.longitude = limitbonds.southwest.longitude
        this.setData({
          location
        })
    }
    else if(longitude >limitbonds.norteast.longitude ){
        //超出东北角经度范围,设置为东北角经度
        
        location.longitude = limitbonds.norteast.longitude
        this.setData({
          location
        })
    }

  },

  gettitles(selectyear){
    var year = selectyear?selectyear : new Date().getFullYear();
    var startyear = 2022 ;
    
    var content = '第' +  convertToChinaNum(year-startyear +1 ) + '届';
    return content;
},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getschedule();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },


  
  //data
  getmatchesdata:function(){
    var that = this;
    app.getmatchesdata(this.data.selectarea,this.data.selectyear,function(res){
      console.log("getmatchesdata-res",res);
      if(res.data.data){

        that.setData({tourdata:res.data.data});
      }
      else{
     
        that.setData({tourdata:""});
      }
 },function(){

 }) ;
  },

  
     //打开playerscorecard 页面 
     _openmatchbyscores(e) {
      let matchid = e.currentTarget.dataset.matchid;
      console.log(matchid);
        wx.navigateTo({
          url: '../Tournament/match?matchid='+matchid
        })
      // 将参数的形式传递给父组件
    },
   //打开playerscorecard 页面 
   _openplayerCardbyscores(e) {
    console.log(e);
    let playerorteam = 0; //是否是team团队成绩卡
    let selectid = e.currentTarget.dataset.player_id;
    let matchid = e.currentTarget.dataset.matchid;
    let playername = e.currentTarget.dataset.playername;
    wx.navigateTo({
      url: '../Scorecard/player/index?selectid=' + selectid + "&playerorteam=" + playerorteam +
        "&playername=" + playername + "&matchid=" + matchid,
    })
    // 将参数的形式传递给父组件
  },

  getmatchesscoredata:function(){
    var that = this;
    /*app.getmatchesscoredata(this.data.selectarea,this.data.selectyear,function(res){
      console.log("getmatchesscoredata-res",res);
      if(res.data.data){
        var all_scores_max =  res.data.data.all_scores_max;
        all_scores_max.minbmt = getmatchshortname(  all_scores_max.minbmt);
        all_scores_max.mininsmt = getmatchshortname(  all_scores_max.mininsmt);
        all_scores_max.minmt = getmatchshortname(  all_scores_max.minmt);
        all_scores_max.minnetmt = getmatchshortname(  all_scores_max.minnetmt);
        all_scores_max.minouttmt = getmatchshortname(  all_scores_max.minouttmt);
        all_scores_max.diffmt = getmatchshortname(  all_scores_max.diffmt);
        
        that.setData({tourscoredata:all_scores_max});
      }
      else{
     
        that.setData({tourscoredata:""});
      }
 },function(){

 }) ;*/
 app.getmatchesplayeredata(this.data.selectarea,this.data.selectyear,function(res){
  console.log("getmatchesplayeredata-res",res);
  if(res.data.data){
    var all_players_max =  res.data.data.all_players_max;
    all_players_max.fmt = getmatchshortname(  all_players_max.fmt);
    all_players_max.mintmt = getmatchshortname(  all_players_max.mintmt);
    all_players_max.mmt = getmatchshortname(  all_players_max.mmt);
    all_players_max.pmt = getmatchshortname(  all_players_max.pmt);
    that.setData({tourplayersdata:res.data.data.all_players_max});
  }
  else{
 
    that.setData({tourplayersdata:""});
  }
},function(){

}) ;


 
  },



 ///打开注册页面
 _openmatchreg(e) {
  let matchinfo = e.detail.matchinfo;
  app.globalData.selectmatchinfo = matchinfo;
  wx.navigateTo({
    url: '../Tournament/match'
  })

},

changedisplay:function(e){
  const {type} = e.currentTarget.dataset;
 
  this.setData({listtype:type})
},

changefull:function(){

  this.setData({isfull:!this.data.isfull})
  this.getTabBar().setData({ ishow: !this.data.isfull });
  console.log(  this.getTabBar() );
  console.log(  this.getTabBar().data.ishow );
},

 //获取正在报名的比赛
 getmatchinforeg(isautorefresh) {
  var that = this;
  app.getmatchinforeg(new Date().getFullYear(),this.data.selectarea,function (res) {
   console.log("getmatchinforeg");
   console.log(res.data.data.monthmatches);
    if(res.data.data.monthmatches){
      var monthmathes = res.data.data.monthmatches;
      var matchinfo = [];
      for(var index=0;index<monthmathes.length;index++){
          var matches = monthmathes[index].matches;
          for(var matchindex=0;matchindex<matches.length;matchindex++){
          if(matches[matchindex].matchstatuscode=='R'){
            console.log("matches[matchindex]");
            console.log(matches[matchindex]);
            matchinfo.push(matches[matchindex]);
          }
        }
      }
      that.setData({
        matchinforeg: matchinfo
      })
    console.log("getmatchinfo-matchinfo");
    console.log(that.data.matchinforeg);
    }
    else{
      that.setData({
        matchinforeg: []
      })
    }
  
},function () {
  if (!isautorefresh) {
   
    wx.hideLoading();
  }
});
 
},



setmatchesmarkes(){
  let{markers,schuedelDataByMonth,customCallout,locallocation,lables} = this.data;
  lables =  markers = [];
  var latieds = [];
  var index=0;
  const mapcontext = wx.createMapContext('matchmap');

  if(!schuedelDataByMonth  || !schuedelDataByMonth.monthmatches || schuedelDataByMonth.monthmatches.length<=0){
    //this.setData({markers});
    mapcontext.addMarkers({markers:markers,clear:true});
    return ;

  }
  schuedelDataByMonth.monthmatches.forEach(month=>{
     month.matches.forEach(item=>{
     
      if(item.courseinfo.courseadress && item.courseinfo.courseadress.latitude && item.courseinfo.courseadress.longitude){
        var distance =locallocation? this.disctance(locallocation.latitude,locallocation.longitude,item.courseinfo.courseadress.latitude,item.courseinfo.courseadress.longitude):'';
        var isfinnals = (item.matchtype==3||item.matchtype==4);
        var indexfirst =  item.matchname.indexOf('【');
        var indexlast =  item.matchname.indexOf('】');
     
        item.shortmatchname = indexfirst >0 &&  indexlast >0 ? item.matchname.substring(indexfirst,indexlast+1):item.matchname;
        if(latieds[item.courseinfo.courseadress.latitude+'-'+item.courseinfo.courseadress.longitude]){
            if(markers[latieds[item.courseinfo.courseadress.latitude+'-'+item.courseinfo.courseadress.longitude]-1]){
              if(markers[latieds[item.courseinfo.courseadress.latitude+'-'+item.courseinfo.courseadress.longitude]-1].match instanceof Array ){  //是数组 直接push
                  markers[latieds[item.courseinfo.courseadress.latitude+'-'+item.courseinfo.courseadress.longitude]-1].match.push(item);
              } 
              else{  //不是数组
                  var iteminner = [markers[latieds[item.courseinfo.courseadress.latitude+'-'+item.courseinfo.courseadress.longitude]-1].match];
                  iteminner.push(item);
                  markers[latieds[item.courseinfo.courseadress.latitude+'-'+item.courseinfo.courseadress.longitude]-1].match = iteminner;
              }
            }
        }
        else{
            markers.push({
              iconPath:'../../images/icon_bg_map'+ (isfinnals?'_n':'') +'.png',
              id:index++,
              latitude:item.courseinfo.courseadress.latitude,
              longitude:item.courseinfo.courseadress.longitude,
              matchname:item.matchname,
              matchtype:item.matchtype,
              customCallout:customCallout,
              width:'40rpx', //80
              height:'68rpx',//136
             // width:'80rpx',
             /// height:'136rpx',
              match:[item],
              distance:distance,
              
            })
            latieds[item.courseinfo.courseadress.latitude+'-'+item.courseinfo.courseadress.longitude] = index;
      }
      
      item.distance = distance;
    }
     })
    
  })

  //this.setData({markers,schuedelDataByMonth});
    mapcontext.addMarkers({markers:markers,clear:true});
  this.setData({schuedelDataByMonth});//markers,
  console.log(markers);
  console.log(schuedelDataByMonth);
},

disctance(lat1, lng1, lat2, lng2){
console.log(lat1, lng1, lat2, lng2)
var radLat1 = lat1 * Math.PI/180.0;
var radLat2 = lat2 * Math.PI/180.0;
var a = radLat1 - radLat2;
var b = lng1 * Math.PI/180.0- lng2 * Math.PI/180.0;
var s =2* Math.asin(Math.sqrt(Math.pow(Math.sin(a /2),2)+ Math.cos(radLat1)* Math.cos(radLat2)* Math.pow(Math.sin(b /2),2)));
s = s *6378.137;
s = Math.round(s *10000)/10000;
return s.toFixed(0)
},

///获取首页图片
getIndexpics() {
  var that = this;
 
  
  app.getIndexpics(
    function(res){
        if(res.data.data.news){
          var indexpageUrl= [];
          var thurmbs = res.data.data.news;
          for(var index= 0;index<thurmbs.length;index++)
          {
            indexpageUrl.push(thurmbs[index]);
          }
            that.setData({indexpageUrl:indexpageUrl});
            console.log("that.data.indexpageUrl");
            console.log(that.data.indexpageUrl);
        }
        else{
          console.log("that.data.indexpageUrl:[]");
          that.setData({indexpageUrl:[]});
        }
    })
  

},

/**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    var that = this;
    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var shareObj = {
      title: "赛程-" +    app.langpagcke.apptitle[0]  + " " + app.langpagcke.apptitle[1] + '官方小程序' , // 默认是小程序的名称(可以写slogan等)
      path: '/pages/Schedul/index', // 默认是当前页面，必须是以‘/’开头的完整路径
      imageUrl:'/images/thurmb.png',
      //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {
          console.log(res);
        }
      },
      fail: function () {
        // 转发失败之后的回调
        if (res.errMsg == 'shareAppMessage:fail cancel') {
          // 用户取消转发
        } else if (res.errMsg == 'shareAppMessage:fail') {
          // 转发失败，其中 detail message 为详细失败信息
        }
      },
      complete: function () {
        // 转发结束之后的回调（转发成不成功都会执行）
      }

    };
    // 来自页面内的按钮的转发
    if (options.from == 'button') {
      var eData = options.target.dataset;
      console.log(eData.id); // shareBtn
      // 此处可以修改 shareObj 中的内容
     
    }
    // 返回shareObj
    return shareObj;
  },
 /**
   * 用户分享朋友圈
   */
  onShareTimeline(){
  
    var that = this;
    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var shareObj = {
      title: "赛程-"    +  app.langpagcke.apptitle[0]  + " " + app.langpagcke.apptitle[1] + '官方小程序' , // 默认是小程序的名称(可以写slogan等)
      query: 'userID='+ app.globalData.userInfo.userID , // 默认是当前页面，自定义页面路径中携带的参数，如 path?a=1&b=2 的 “?” 后面部分
      imageUrl:'/images/iconlogo.png',
      //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
    };
   
    // 返回shareObj
    return shareObj;
},


  //打开微信的新闻页面
  _opennewsindex(e) {


    let news_itemobj = e.currentTarget.dataset.newsitem;; //JSON.parse(newsitem.replace(" ", "").replace(/\ufeff/g, ""));
    console.log("_opennews");
    console.log(news_itemobj);
    if (news_itemobj.url) {
      this.setData({
        news_url: news_itemobj.url
      });
      console.log('../URL/index?weburl=' + encodeURIComponent(news_itemobj.url));
      app.globalData.selectnewcontentobj = news_itemobj;
    wx.navigateTo({
        url: '../URL/index?weburl='+encodeURIComponent(news_itemobj.url)+"&type=新闻&title="+ news_itemobj.title
      })
     // wx.navigateTo({
      //  url: '../URL/newpage/index?weburl=' + encodeURIComponent(news_itemobj.url) + "&title=" + news_itemobj.title + "&type='" + '新闻页面'
     // })

    } else {

    }
  },

  bindDateChange:function(e){
    var selectyearindex = e.detail.value;
    var selectyear = this.data.selectyearlists[selectyearindex];
    console.log(e);
    this.setData({selectyear:selectyear,
    titlecontent: this.gettitles(selectyear) + "君品习酒中国精英公开赛"
    });
    this.getschedule(selectyear);
    
  },

  bindareaChange:function(e){
    var selectareaindex = e.detail.value;
    var selectarea  = this.data.schuedelDataByMonth.areas[selectareaindex];
    console.log(e);
    this.setData({selectarea:selectarea,
       
    });
    this.getschedule(this.data.selectyear);
    this.getmatchinforeg();
  },

  ///获取赛程 所有的赛程列表
  getschedule(year) {

    var that = this;
    wx.showLoading({
      title: '加载中',
    })
   
    if(!year){
      year = new Date().getFullYear();
    }
        app.getmatchlists(year, "", 1 ,function(res){
            console.log("getschedule");
            console.log(res);
            if(res.data.data){
                 
                that.setData({schuedelDataByMonth:res.data.data,
                  titlecontent:  that.gettitles(year) +   "君品习酒中国精英公开赛"
                });
                that.setmatchesmarkes();
                if(res.data.data.selectyearlists){
                  that.setData({selectyearlists:res.data.data.selectyearlists});
                }
            }
            else{
              that.setData({schuedelDataByMonth:[]});
              that.setmatchesmarkes();
            }
        },function(){
            wx.hideLoading();
        },this.data.selectarea,this.data.selectmt_type)
      
        this.getmatchesdata();
        this.getmatchesscoredata();

        
    
  },


  
  change3d:function(e){
    var enable = e.detail.value;
    //console.log(!this.data.setting.enable3D);
  
    console.log(enable);
    this.setData({
      // 仅设置的属性会生效，其它的不受影响
      setting: {
        enable3D: enable,
        skew:!enable?0:40,
        //enableTraffic: true
      }
    })
  },

  changesalite:function(e){
    var enableSatellite = e.detail.value;
    this.setData({
      // 仅设置的属性会生效，其它的不受影响
      setting: {
        enableSatellite: enableSatellite,
       
        //enableTraffic: true
      }
    })
  },

  changelocation:function(e){
    let {markers} = this.data;
      const {markerId} = e.detail ;
      console.log(markerId);
      var matches = markers.filter(item=>{ return item.id ==markerId  })[0];
      if(matches){
        this.setData({
          location:{
            longitude:matches.match[0].courseinfo.courseadress.longitude,
            latitude:matches.match[0].courseinfo.courseadress.latitude,
          }
         
        });
       
        // this.onRegionChange('',true)
        console.log(this.data.location);
      }
  },


  movetomonth:function(e){
      var monthindex= e.currentTarget.dataset.monthindex;
      var yearindex= e.currentTarget.dataset.yearindex;
      this.setData({currentselectmongthindex:monthindex});
      var me = this;
   var query = wx.createSelectorQuery().in(me);
   query.selectViewport().scrollOffset()
   query.select("#vmonthscheudul"+yearindex+monthindex).boundingClientRect();
   query.exec(function (res) {
    console.log(res);
    var miss = res[0].scrollTop + res[1].top -30;
    wx.pageScrollTo({
     scrollTop: miss,
     duration: 300
    });
      
   });
  },

  fillheight() {
    var that = this;
    // var yearmatcheslists = that.data.schuedelDataByMonth[this.data.currentTab].monthmatches;
    // var yearindex = that.data.schuedelDataByMonth[this.data.currentTab].yearindex;
    // var height=0;
    var that = this;
    var obj = this.createSelectorQuery().select("#vyearscheudulcontain" + that.data.currentTab);

    obj.boundingClientRect(function (rect) {
      if (rect == null || rect.height == null) {
        return;
      }
      var fullheight = wx.getSystemInfoSync().windowHeight;
      var windowswidth = wx.getSystemInfoSync().windowWidth;
      var pixelRatio = windowswidth / 750; // wx.getSystemInfoSync().pixelRatio;



      that.setData({
        currentpageheight: (rect.height) / pixelRatio // 节点的高度
      });
      console.log(rect.height);
      console.log(that.data.currentpageheight);


    }).exec();





  },
  //  tab切换逻辑
  swichNav: function (e) {
    var that = this;
    if (that.data.currentTab === e.target.dataset.current) {

      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current
      })
      that.fillheight();
    }

  },

  bindChange: function (e) {
    var that = this;
    that.setData({
      currentTab: e.detail.current
    });
    that.fillheight();
  },
  ///打开matchcard
  _openmatch(e) {
    wx.requestSubscribeMessage({
      tmplIds: ['LFT3BEcr7jfe4AtrHealLmgBsYujzpfPNIcC9c1GYR4'],
      success (res) { },
      fail(res){console.log(res)}
    });
    let matchinfo = e.detail.matchinfo;
    app.globalData.selectmatchinfo = matchinfo;
    wx.navigateTo({
      url: '../Tournament/match'
    })
  },

  
  openmatch:function(e){
    let {markers} = this.data;
    const {markerId} = e.detail ;
    console.log(markerId);
    var matches = markers.filter(item=>{ return item.id ==markerId  })[0];
    if(matches){
      let matchinfo =matches.match[0];
      console.log(matchinfo);
      app.globalData.selectmatchinfo = matchinfo;
      wx.navigateTo({
        url: '../Tournament/match'
      })
    }
},

   ///打开直播页面
   _openlive(e){
    let matchinfo = e.detail.matchinfo;
    app.globalData.selectmatchinfo = matchinfo;
    wx.navigateTo({
      url: '../Tournament/live/index'
    })
  },


  //搜索的方法
  _search: function () {
    let searchcontent = e.detail.searchcontent;
    wx.showToast({
      title: searchcontent,
      icon: 'none'
    })
  },

  
    
  onPageScroll (e) { 
   // console.log(e);
     var that= this;
      wx.createSelectorQuery().select('#tourbanner').boundingClientRect(function(rect){
        
          if(rect){
              if(rect.top + rect.height <=0)     // 节点的上边界坐标{
              {
                that.setData({istop:true});
              }
              else{
                that.setData({istop:false});
              }
          }
        
    }).exec();
    },

})